package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.StationResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.WechatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "维修站相关接口")
@RestController
@RequestMapping("/station")
public class StationController extends BaseController {

    @Autowired
    private StationService stationService;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;


    @ApiOperation("使用关键字查询所有站点")
    @RequestMapping(value = "findStations", method = RequestMethod.GET)
    public JsonResponse findStations(Principal principal,
                                     @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName){
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        return stationService.findStations(stationName);
    }
    @ApiOperation("按条件查询维修站")
    @RequestMapping(value = "findOneStation", method = RequestMethod.GET)
    public JsonResponse findOneStation(Principal principal,
                                       @ApiParam("省") @RequestParam(value = "province", required = false) String province,
                                       @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
                                       @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                       @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
                                       @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
                                       @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
                                       @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                       @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
                                       @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                       @ApiParam("创建人员姓名") @RequestParam(value = "userName", required = false) String userName,
                                       @ApiParam("用户身份") @RequestParam(value = "userType", required = false) Integer userType,
                                       @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
//        if (StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(category) && StringUtils.isEmpty(brand) && StringUtils.isEmpty(stationName)) {
//            return JsonResponse.successResponseWithData(new Object[0]);
//        }
        if (StringUtils.isNotEmpty(brand)) {
            try {
                QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(Long.valueOf(brand));
                if (null != questionAnswerOption && StringUtils.isNotEmpty(questionAnswerOption.getName())) {
                    brand = questionAnswerOption.getName();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //TODO 暂时不知道这段代码是什么作用，先把身份的判定加入
//        if (clientUser.getUserType().equals(UserType.dealers)) {
//            UserProfile userProfile = userProfileRepository.findByUserId(clientUser.getId());
//            List<Station> stationList = userProfile.getDepartmentList().get(0).getStationList();
//            Map<Long, Station> searchStation = new HashMap<>();
//            for (Station station : stationList) {
//                if (StringUtils.isNotEmpty(stationName)) {
//                    int indexOf = station.getName().indexOf(stationName);
//                    if (indexOf != -1) {
//                        searchStation.put(station.getId(), station);
//                    }
//                }
//                if (StringUtils.isNotEmpty(province)) {
//                    int indexOf = station.getProvince().indexOf(province);
//                    if (indexOf != -1) {
//                        searchStation.put(station.getId(), station);
//                    }
//                }
//                if (StringUtils.isNotEmpty(brand)) {
//                    int indexOf = station.getBrand().indexOf(brand);
//                    if (indexOf != -1) {
//                        searchStation.put(station.getId(), station);
//                    }
//                }
//            }
//            QStation qStation = QStation.station;
//            BooleanBuilder builder = new BooleanBuilder();
//            builder.and(qStation.enabled.eq(true));
//            builder.and(qStation.deleted.eq(false));
//            if (null != userType){
//                builder.and(qStation.report_finished.eq((userType - 1)).or(qStation.report_finished.eq(3)));
//            }
//            if (StringUtils.isNotEmpty(stationName)) {
//                builder.and(qStation.name.like("%" + stationName + "%"));
//            }
//            if (StringUtils.isNotEmpty(province)) {
//                builder.and(qStation.province.like("%" + province + "%"));
//            }
//            if (StringUtils.isNotEmpty(city)) {
//                builder.and(qStation.city.like("%" + city + "%"));
//            }
//            if (StringUtils.isNotEmpty(category)) {
//                builder.and(qStation.category.like("%" + category + "%"));
//            }
//            if (StringUtils.isNotEmpty(brand)) {
//                builder.and(qStation.brand.like("%" + brand + "%"));
//            }
//            List<Station> stations = (List<Station>) stationRepository.findAll(builder);
////            for (Station station : stations) {
////                searchStation.put(station.getId(), station);
////            }
////            List<StationResponse> dealersList = new ArrayList<>();
////            for (Station key : searchStation.values()) {
////                StationResponse stationResponse = new StationResponse();
////                stationResponse.setId(key.getId());
////                stationResponse.setName(key.getName());
////                dealersList.add(stationResponse);
////            }
//            return JsonResponse.successResponseWithData(stations);
//        }
        return stationService.findOneStation(province, city, category, brand, stationName, clientUser,userType,
                customerStat, customerType, paintBrand, productPosition, stationNum, userName);
    }

    @ApiOperation("检查维修站信息是否完整")
    @RequestMapping(value = "checkStationInfo", method = RequestMethod.GET)
    public JsonResponse checkStationInfo(Principal principal,
                                         @ApiParam("维修站ID") @RequestParam(value = "stationId") Long stationId) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.CREATE_CUSTOMER);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:新增客户权限");
        }
        if (stationId == null || stationId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "stationId参数错误");
        }
        Station station = stationRepository.findOne(stationId);
        if (station == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到该维修站");
        }
        if (station.isCheckStation() == false) {
            return JsonResponse.errorResponseWithError("抱歉", "维修站信息不完整");
        }
        return JsonResponse.successResponse();
    }

    @Autowired
    private WechatService wechatService;

    @RequestMapping(value = "testWeChat", method = RequestMethod.GET)
    public void testWeChat() {
        User user = new User();
        user.setOpenId("omSAT1oYpSuaR8lELjWYQsyVk-Pg");
        String firstData = "您好，您有一份在XXX进行的XXX规服务报告。";
        wechatService.pushWechatMessage(user, "jUjiQshE94Fr5PhYigl0aLU_OZeybefechS7Oz1v4x4", Constants.WECHAT_PUSH_URL, firstData,
                "可登录漆星服务系统进行查看", "客户超过24小时未打分", "张三", "2018-12-18", "", "");
    }


}
